package dp;

/**
 * @author pengfei.hpf
 * @date 2020/2/9
 * @verdion 1.0.0
 * A message containing letters from A-Z is being encoded to numbers using the following mapping:
 *
 * 'A' -> 1
 * 'B' -> 2
 * ...
 * 'Z' -> 26
 * Given a non-empty string containing only digits, determine the total number of ways to decode it.
 *
 * Example 1:
 *
 * Input: "12"
 * Output: 2
 * Explanation: It could be decoded as "AB" (1 2) or "L" (12).
 * Example 2:
 *
 * Input: "226"
 * Output: 3
 * Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/decode-ways
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class NumDecodings {

    public int numDecodings(String s) {
        if(s == null || s.length() == 0 || s.startsWith("0")){
            return 0;
        }
        int lastOne = 1;
        int lastTwo = 1;
        int res = 1;
        for(int i = 1; i < s.length(); i ++){
            int v = s.charAt(i) - '0';
            int l = s.charAt(i - 1) - '0';
            int withL = l * 10 + v;
            if(v == 0 && (withL > 26 || withL < 1)){
                return 0;
            } else if(v != 0 && withL <= 26 && l != 0){
                res = lastOne + lastTwo;
            } else if(v == 0) {
                res = lastTwo;
                lastOne = res;
            }
            lastTwo = lastOne;
            lastOne = res;
        }
        return res;
    }
}
